var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
// sql
const query = require('../mysql');
// 上传模块
const multer = require('multer');
const upload = multer({
	dest: path.join(__dirname, '../../public/file/work'),
});

let workAddForm;
// 获取
router.get('/', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	let inputQuery = req.query.queryInfo.query;
	let searchType = req.query.searchType;
	let username = req.query.username;
	// console.log(req.query);
	let result;
	if (inputQuery == '') {
		let sqlStr = `select * from work where author like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${username}%`]);
	} else {
		let sqlStr = `select * from work where ${searchType} like ? and author like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`, `%${username}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from essay`;
	let result1 = await query(sqlStr1);

	// if (result.length == 0) {
	// 	res.send({ status: 100, message: '获取著作信息失败' });
	// }
	console.log(result);
	res.send({ status: 200, result, total: result1[0]['count(*)'] });
});

// 上传
router.post('/', async (req, res, next) => {
	workAddForm = req.body.workAddForm;
	let sqlStr = `select * from work where no=?`;
	let result = await query(sqlStr, [workAddForm.no]);
	if (result.length != 0) {
		return res.send({ status: 401, message: '获奖名称重复' });
	}
	res.send({ status: 200, message: '创建信息成功' });
});

router.post('/upload', upload.single('file'), async (req, res, next) => {
	file = req.file;
	saveWork(file, req, res);
});

async function saveWork(file, req, res) {
	let {
		name,
		no,
		author,
		author_type,
		affiliated_unit,
		publish_time,
		copyright_category,
		copyright_type,
		national_planning_textbook,
		subject_classification,
		status,
		remarks,
	} = workAddForm;
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/work/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `insert into work(name,no,author,author_type,affiliated_unit,publish_time,copyright_type,copyright_category,national_planning_textbook,subject_classification,status,workfile,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)`;

	let result = await query(sqlStr, [
		name,
		no,
		author,
		author_type,
		affiliated_unit,
		publish_time,
		copyright_category,
		copyright_type,
		national_planning_textbook,
		subject_classification,
		status,
		`file/work/${name}.${extName}`,
		remarks,
	]);
	if (result.length == 0) {
		console.log('faile');
		res.send({ status: 404, message: 'faile' });
		return;
	}
	res.send({ status: 200, message: 'upload award success' });
}

// 修改获奖
let workEditForm;
router.post('/edit', async (req, res) => {
	workEditForm = req.body.workEditForm;
	res.send({ status: 100, message: '创建信息成功' });
});

router.post('/edit/upload', upload.single('file'), async (req, res) => {
	file = req.file;
	saveEditFile(file, req, res);
});

async function saveEditFile(file, req, res) {
	let {
		name,
		no,
		author,
		author_type,
		affiliated_unit,
		publish_time,
		copyright_category,
		copyright_type,
		national_planning_textbook,
		subject_classification,
		status,
		remarks,
		workfile,
	} = workEditForm;

	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/work/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});
	let prevFile = path.join(__dirname, `../../public${workfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});
	let sqlStr = `update work set name = ?,no = ?,author = ?,author_type = ?,affiliated_unit = ?,publish_time = ?,copyright_category=?,copyright_type = ?,national_planning_textbook = ?,subject_classification = ?,status = ?,remarks =?,workfile=? where id = ?`;

	let result = await query(sqlStr, [
		name,
		no,
		author,
		author_type,
		affiliated_unit,
		publish_time,
		copyright_category,
		copyright_type,
		national_planning_textbook,
		subject_classification,
		status,
		remarks,
		`/file/work/${name}.${extName}`,
		workEditForm.id,
	]);
	// console.log(result);
	res.send({ status: 200, message: 'success' });
}

// 删除著作
router.delete('/', async (req, res) => {
	let reqQuery = req.query;

	let prevFile = path.join(__dirname, `../../public${reqQuery.workfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});
	// console.log(query);
	let sqlStr = `delete from work where id = ?`;
	let result = query(sqlStr, [reqQuery.id]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});

module.exports = router;
